package com.uzai.console.service.fd.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.fd.fdautoconfig.FdAutoConfigDto;
import com.uzai.console.dto.fd.fdautoconfig.FdAutoConfigIdDto;
import com.uzai.console.dto.fd.fdautoconfig.FdAutoConfigQuery;
import com.uzai.console.dto.fd.fdautoconfig.FdAutoConfigStatusDto;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.EsTiktokConversation;
import com.uzai.console.enums.FdGoodsParaEnum;
import com.uzai.console.jsonvo.fd.fdtemplate.FdTemplateData;
import com.uzai.console.mapper.*;
import com.uzai.console.service.fd.FdAutoConfigService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.vo.fd.fdautoconfig.FdAutoConfigVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 朋友圈自动发圈配置
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class FdAutoConfigServiceImpl implements FdAutoConfigService {

    Logger logger = LoggerFactory.getLogger(FdAutoConfigServiceImpl.class);

    @Autowired
    private FdAutoConfigMapper fdAutoConfigMapper;
    @Autowired
    private FdDevicePlanMapper fdDevicePlanMapper;
    @Autowired
    private FdDevicePlanGroupMapper fdDevicePlanGroupMapper;
    @Autowired
    private WxqGroupManagePlanMapper wxqGroupManagePlanMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private WxqWorkGroupManagePlanMapper wxqWorkGroupManagePlanMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询朋友圈自动发圈配置列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdAutoConfigQuery
     * @return null
     */
    public Page<FdAutoConfigVo> findFdAutoConfigByPage(FdAutoConfigQuery fdAutoConfigQuery){
        //新建返回到页面的LIST对象
        List<FdAutoConfigVo> fdAutoConfigPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<FdAutoConfig> page = new Page<>();
        fdAutoConfigQuery.convert(page);
        ArrayList<FdAutoConfig> fdAutoConfigList =  fdAutoConfigMapper.findByList(page, fdAutoConfigQuery);
        if(fdAutoConfigList != null && fdAutoConfigList.size() > 0){
            for (FdAutoConfig fdAutoConfig : fdAutoConfigList){
                FdAutoConfigVo fdAutoConfigVo = new FdAutoConfigVo();
                BeanUtils.copyProperties(fdAutoConfig, fdAutoConfigVo);

                //设备方案名称
                if(fdAutoConfig.getFdDevicePlanId() != null){
                    FdDevicePlan fdDevicePlan = fdDevicePlanMapper.selectById(fdAutoConfig.getFdDevicePlanId(), fdAutoConfig.getMerId());
                    if(fdDevicePlan != null){
                        fdAutoConfigVo.setFdDevicePlanName(fdDevicePlan.getName());
                    }
                }

                try {
                    if(fdAutoConfig.getData() != null){
                        List<FdTemplateData> fdTemplateDataList =  JSONObject.parseArray(fdAutoConfig.getData(), FdTemplateData.class);
                        fdAutoConfigVo.setFdTemplateDataList(fdTemplateDataList);
                    }
                }catch (Exception e){

                }

                fdAutoConfigPageVoList.add(fdAutoConfigVo);
            }
        }
        //返回到页面分页对象
        Page<FdAutoConfigVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(fdAutoConfigPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询朋友圈自动发圈配置详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdAutoConfigIdDto
     * @return null
     */
    public FdAutoConfigVo findFdAutoConfig(FdAutoConfigIdDto fdAutoConfigIdDto){
        if(fdAutoConfigIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        FdAutoConfig fdAutoConfig = fdAutoConfigMapper.selectById(fdAutoConfigIdDto.getId(), fdAutoConfigIdDto.getMerId());

        if(fdAutoConfig == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该朋友圈自动发圈配置不存在");
        }

        FdAutoConfigVo fdAutoConfigVo = new FdAutoConfigVo();
        BeanUtils.copyProperties(fdAutoConfig, fdAutoConfigVo);

        //设备方案名称
        if(fdAutoConfig.getFdDevicePlanId() != null){
            FdDevicePlan fdDevicePlan = fdDevicePlanMapper.selectById(fdAutoConfig.getFdDevicePlanId(), fdAutoConfig.getMerId());
            if(fdDevicePlan != null){
                fdAutoConfigVo.setFdDevicePlanName(fdDevicePlan.getName());
            }
        }

        try {
            if(fdAutoConfig.getData() != null){
                List<FdTemplateData> fdTemplateDataList =  JSONObject.parseArray(fdAutoConfig.getData(), FdTemplateData.class);
                fdAutoConfigVo.setFdTemplateDataList(fdTemplateDataList);
            }
        }catch (Exception e){

        }

        return fdAutoConfigVo;
    }

    /**
     * 添加朋友圈自动发圈配置
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdAutoConfigDto
     * @return null
     */
    public void addFdAutoConfig(FdAutoConfigDto fdAutoConfigDto){

        if(fdAutoConfigDto.getFdDevicePlanId() == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择发单设备方案");
        }

        if(StringUtils.isBlank(fdAutoConfigDto.getLimitTimeStart())){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请设置发送时间");
        }

        FdDevicePlan fdDevicePlan = fdDevicePlanMapper.selectById(fdAutoConfigDto.getFdDevicePlanId(), fdAutoConfigDto.getMerId());
        if(fdDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "发单设备方案不存在");
        }

        //查询该配置方案关联的群信息
        List<FdDevicePlanGroup> fdDevicePlanGroupList = fdDevicePlanGroupMapper.findByListByFdDevicePlanId(fdDevicePlan.getId(), fdDevicePlan.getMerId());
        if(fdDevicePlanGroupList == null || fdDevicePlanGroupList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案未配置任何群信息");
        }

        for (FdDevicePlanGroup fdDevicePlanGroup : fdDevicePlanGroupList) {
            //判断此群的配置方案是否开启了群发功能，如果未开启，则抛出异常
            if(fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())){//个人微信

                //缓存中的微信群管理方案key
                String redisKey_wxgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), fdAutoConfigDto.getMerId(), fdDevicePlanGroup.getDeviceId(), fdDevicePlanGroup.getWxid());
                Object wxgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxgroup_manageplan_key);
                if(wxgroup_manageplan_id == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群还未配置管理方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                ConfigPlan configPlan = configPlanMapper.selectById((Long)wxgroup_manageplan_id, fdAutoConfigDto.getMerId());
                if(configPlan == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdAutoConfigDto.getMerId());
                if(sysPlugin == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                JSONObject jsonObject = null;
                try {
                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
                }catch (Exception e){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案保存的数据格式错误，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                if(jsonObject == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
                if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案未开启社群群发功能，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

            }else if(fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())){//企业微信

                //缓存中的企业微信群管理方案key
                String redisKey_wxworkgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), fdAutoConfigDto.getMerId(), fdDevicePlanGroup.getDeviceId(), fdDevicePlanGroup.getWxid());
                Object wxworkgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxworkgroup_manageplan_key);
                if(wxworkgroup_manageplan_id == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群还未配置管理方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                ConfigPlan configPlan = configPlanMapper.selectById((Long)wxworkgroup_manageplan_id, fdAutoConfigDto.getMerId());
                if(configPlan == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdAutoConfigDto.getMerId());
                if(sysPlugin == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                JSONObject jsonObject = null;

                try {
                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
                }catch (Exception e){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案保存的数据格式错误，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                if(jsonObject == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
                if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案未开启社群群发功能，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
            }else if(fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.TIKTOK.getKey())){//抖音设备
                String esName = EsIndexName.UZAI_TIKTOK_CONVERSATION;
                String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, fdAutoConfigDto.getMerId());
                Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(mechantOtherEsIndexName, fdDevicePlanGroup.getGroupId(), null);
                EsTiktokConversation esTiktokConversation  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsTiktokConversation.class);
                if(esTiktokConversation == null || Tools.getLong(esTiktokConversation.getManagePlanId()) == 0 ){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群还未配置管理方案，群会话id为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                ConfigPlan configPlan = configPlanMapper.selectById(esTiktokConversation.getManagePlanId(), fdAutoConfigDto.getMerId());
                if(configPlan == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdAutoConfigDto.getMerId());
                if(sysPlugin == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                JSONObject jsonObject = null;
                try {
                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
                }catch (Exception e){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案保存的数据格式错误，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                if(jsonObject == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
                if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案未开启社群群发功能，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
            }
        }

        //查询所有发送内容
        List<FdTemplateData> fdTemplateDataList = fdAutoConfigDto.getFdTemplateDataList();
        if(fdTemplateDataList == null || fdTemplateDataList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入发送内容");
        }

        Integer now = DateUtil.getNowTime();
        FdAutoConfig fdAutoConfig = new FdAutoConfig();
        fdAutoConfig.setId(IdWorker.getId());
        fdAutoConfig.setMerId(fdAutoConfigDto.getMerId());
        fdAutoConfig.setName(fdAutoConfigDto.getName());
        fdAutoConfig.setFdDevicePlanId(fdAutoConfigDto.getFdDevicePlanId());
        fdAutoConfig.setLimitTimeStart(fdAutoConfigDto.getLimitTimeStart());
        fdAutoConfig.setLimitTimeEnd("23:59");
        fdAutoConfig.setStatus(0);//添加默认为0
        fdAutoConfig.setData(Tools.getStrNull(JSONObject.toJSONString(fdAutoConfigDto.getFdTemplateDataList())));
        fdAutoConfig.setCreateTime(now);
        fdAutoConfig.setUpdateTime(now);
        fdAutoConfigMapper.insert(fdAutoConfig);
    }

    /**
     * 修改朋友圈自动发圈配置
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdAutoConfigDto
     * @return null
     */
    public void updateFdAutoConfig(FdAutoConfigDto fdAutoConfigDto){
        if(fdAutoConfigDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }


        if(StringUtils.isBlank(fdAutoConfigDto.getLimitTimeStart())){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请设置发送时间");
        }

        FdDevicePlan fdDevicePlan = fdDevicePlanMapper.selectById(fdAutoConfigDto.getFdDevicePlanId(), fdAutoConfigDto.getMerId());
        if(fdDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "发单设备方案不存在");
        }

        //查询该配置方案关联的群信息
        List<FdDevicePlanGroup> fdDevicePlanGroupList = fdDevicePlanGroupMapper.findByListByFdDevicePlanId(fdDevicePlan.getId(), fdDevicePlan.getMerId());
        if(fdDevicePlanGroupList == null || fdDevicePlanGroupList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案未配置任何群信息");
        }

        for (FdDevicePlanGroup fdDevicePlanGroup : fdDevicePlanGroupList) {
            //判断此群的配置方案是否开启了群发功能，如果未开启，则抛出异常
            if(fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())){//个人微信

                //缓存中的微信群管理方案key
                String redisKey_wxgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), fdAutoConfigDto.getMerId(), fdDevicePlanGroup.getDeviceId(), fdDevicePlanGroup.getWxid());
                Object wxgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxgroup_manageplan_key);
                if(wxgroup_manageplan_id == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群还未配置管理方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                ConfigPlan configPlan = configPlanMapper.selectById((Long)wxgroup_manageplan_id, fdAutoConfigDto.getMerId());
                if(configPlan == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdAutoConfigDto.getMerId());
                if(sysPlugin == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                JSONObject jsonObject = null;
                try {
                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
                }catch (Exception e){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案保存的数据格式错误，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                if(jsonObject == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
                if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案未开启社群群发功能，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

            }else if(fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())){//企业微信
                //缓存中的企业微信群管理方案key
                String redisKey_wxworkgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), fdAutoConfigDto.getMerId(), fdDevicePlanGroup.getDeviceId(), fdDevicePlanGroup.getWxid());
                Object wxworkgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxworkgroup_manageplan_key);
                if(wxworkgroup_manageplan_id == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群还未配置管理方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                ConfigPlan configPlan = configPlanMapper.selectById((Long)wxworkgroup_manageplan_id, fdAutoConfigDto.getMerId());
                if(configPlan == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdAutoConfigDto.getMerId());
                if(sysPlugin == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                JSONObject jsonObject = null;

                try {
                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
                }catch (Exception e){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案保存的数据格式错误，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                if(jsonObject == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }

                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
                if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案未开启社群群发功能，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
            }else if(fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.TIKTOK.getKey())){//抖音设备
                String esName = EsIndexName.UZAI_TIKTOK_CONVERSATION;
                String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, fdAutoConfigDto.getMerId());
                Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(mechantOtherEsIndexName, fdDevicePlanGroup.getGroupId(), null);
                EsTiktokConversation esTiktokConversation  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsTiktokConversation.class);
                if(esTiktokConversation == null || Tools.getLong(esTiktokConversation.getManagePlanId()) == 0 ){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群还未配置管理方案，群会话id为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                ConfigPlan configPlan = configPlanMapper.selectById(esTiktokConversation.getManagePlanId(), fdAutoConfigDto.getMerId());
                if(configPlan == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdAutoConfigDto.getMerId());
                if(sysPlugin == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                JSONObject jsonObject = null;
                try {
                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
                }catch (Exception e){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案保存的数据格式错误，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                if(jsonObject == null){
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
                if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                    throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该群管理方案未开启社群群发功能，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId());
                }
            }
        }

        //查询所有发送内容
        List<FdTemplateData> fdTemplateDataList = fdAutoConfigDto.getFdTemplateDataList();
        if(fdTemplateDataList == null || fdTemplateDataList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入发送内容");
        }

        FdAutoConfig fdAutoConfig = fdAutoConfigMapper.selectById(fdAutoConfigDto.getId(), fdAutoConfigDto.getMerId());
        if(fdAutoConfig == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该自动发单配置不存在");
        }
        fdAutoConfig.setMerId(fdAutoConfigDto.getMerId());
        fdAutoConfig.setName(fdAutoConfigDto.getName());
        fdAutoConfig.setFdDevicePlanId(fdAutoConfigDto.getFdDevicePlanId());
        //判断是否改变了发单时间，如果改变了，则清空上次发单时间
        if(!fdAutoConfig.getLimitTimeStart().equals(fdAutoConfigDto.getLimitTimeStart())){
            fdAutoConfig.setLimitTimeStart(fdAutoConfigDto.getLimitTimeStart());
            fdAutoConfig.setSendTime(null);
        }
        fdAutoConfig.setData(Tools.getStrNull(JSONObject.toJSONString(fdAutoConfigDto.getFdTemplateDataList())));
        Integer now = DateUtil.getNowTime();
        fdAutoConfig.setUpdateTime(now);
        fdAutoConfigMapper.updateById(fdAutoConfig);
    }

    /**
     * 删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdAutoConfigIdDto
     * @return null
     */
    public void deleteFdAutoConfig(FdAutoConfigIdDto fdAutoConfigIdDto){
        if(fdAutoConfigIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        fdAutoConfigMapper.deleteById(fdAutoConfigIdDto.getId(), fdAutoConfigIdDto.getMerId());
    }

    /**
     * 设置是否开启
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdAutoConfigStatusDto
     * @return null
     */
    public void updateStatus(FdAutoConfigStatusDto fdAutoConfigStatusDto){
        if(fdAutoConfigStatusDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        FdAutoConfig fdAutoConfig = fdAutoConfigMapper.selectById(fdAutoConfigStatusDto.getId(), fdAutoConfigStatusDto.getMerId());

        if(fdAutoConfig == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此自动发单配置不存在");
        }

        int now = DateUtil.getNowTime();

        fdAutoConfig.setStatus(Tools.getInteger(fdAutoConfigStatusDto.getStatus()));
        fdAutoConfig.setUpdateTime(now);
        //修改状态
        fdAutoConfigMapper.updateStatusById(fdAutoConfig);

        //AOP切面，封装操作日志内容
        String aspectOperatorLog = "修改自动发单任务状态。任务名称:"+fdAutoConfig.getName();
        if(Tools.getInteger(fdAutoConfigStatusDto.getStatus()) == 1){
            aspectOperatorLog = "开启自动发单任务。任务名称:"+fdAutoConfig.getName();
        }else if(Tools.getInteger(fdAutoConfigStatusDto.getStatus()) == 0){
            aspectOperatorLog = "关闭自动发单任务。任务名称:"+fdAutoConfig.getName();
        }
        fdAutoConfigStatusDto.setAspectOperatorLog(aspectOperatorLog);
    }
}
